<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边公司数据-->
      <el-col :xs="9" :sm="6" :md="5" :lg="4" :xl="4">
        <div class="head-container">
          <el-input
            v-model="deptName"
            clearable
            size="small"
            placeholder="输入公司名称搜索"
            prefix-icon="el-icon-search"
            class="filter-item"
            @input="getDeptDatas"
          />
        </div>
        <el-tree
          :data="deptDatas"
          :load="getDeptDatas"
          :props="defaultProps"
          :highlight-current="true"
          :expand-on-click-node="false"
          lazy
          @node-click="handleNodeClick"
        />
      </el-col>
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入用户名、姓名或邮箱搜索"
              style="width: 220px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <el-select
              v-model="query.siteId"
              filterable
              clearable
              size="small"
              placeholder="分站点"
              class="filter-item"
              style="width: 110px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in siteList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-model="query.internalQualification"
              filterable
              clearable
              size="small"
              placeholder="内部资质"
              class="filter-item"
              style="width: 120px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in dict.internal_qualification"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-model="query.roleId"
              filterable
              clearable
              size="small"
              placeholder="平台角色"
              class="filter-item"
              style="width: 140px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in roles"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-select
              v-model="query.enabled"
              filterable
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 90px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in enabledTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
            <date-range-picker v-model="query.createTime" class="date-item" />
            <rrOperation />
          </div>
          <crudOperation show="" :permission="permission" />
        </div>
        <!--表单渲染-->
        <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="584px">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" onkeyup="form.username=this.value=this.value.replace(/\s+/g, '')" :disabled="crud.form.id!==null" style="width: 178px" @blur="form.username = $event.target.value" />
            </el-form-item>
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="form.nickName" onkeyup="form.nickName=this.value=this.value.replace(/\s+/g, '')" style="width: 178px" @blur="form.nickName = $event.target.value" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="form.gender" style="width: 178px">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model.number="form.phone" onkeyup="form.phone=this.value=this.value.replace(/\s+/g, '')" style="width: 178px" @blur="form.phone = $event.target.value" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" onkeyup="form.email=this.value=this.value.replace(/\s+/g, '')" style="width: 178px" @blur="form.email = $event.target.value" />
            </el-form-item>
            <el-form-item label="企微号" prop="wxNo">
              <el-input v-model="form.wxNo" onkeyup="form.wxNo=this.value=this.value.replace(/\s+/g, '')" style="width: 178px" @blur="form.wxNo = $event.target.value" />
            </el-form-item>
            <el-form-item label="公司" prop="dept.id">
              <treeselect
                v-model="form.dept.id"
                :disable-branch-nodes="true"
                :options="depts"
                :load-options="loadDepts"
                style="width: 160px"
                placeholder="选择公司"
                @select="selectDept"
              />
            </el-form-item>
            <el-tooltip effect="dark" content="若添加外部用户所属公司，请先联系股份管理员！" placement="top-start">
              <el-button size="mini" type="text" icon="el-icon-warning" />
            </el-tooltip>
            <el-form-item label="分站点" prop="siteId">
              <el-select v-model="form.siteId" filterable clearable placeholder="请选择" style="width: 178px">
                <el-option
                  v-for="item in siteList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="岗位" prop="jobName">
              <el-input v-model="form.jobName" style="width: 178px" disabled />
              <!--              <el-select
                v-model="form.jobName"
                style="width: 178px"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in jobs"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>-->
            </el-form-item>
            <el-form-item label="专业" prop="discipline">
              <el-select
                v-model="form.discipline"
                style="width: 178px"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dict.discipline"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="内部资质" prop="internalQualification">
              <el-select
                v-model="form.internalQualification"
                style="width: 178px"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dict.internal_qualification"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="执业资格" prop="practiceQualificationDatas">
              <el-select
                v-model="practiceQualificationDatas"
                style="width: 451px"
                multiple
                placeholder="请选择"
                @remove-tag="deletePractice"
                @change="changePracticeQualification"
              >
                <el-option
                  v-for="item in dict.practice_qualification"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-bottom: 18px;" label="平台角色" prop="roleDatas" class="star">
              <el-select
                v-model="roleDatas"
                v-defaultSelect="[roleDefaultSelect]"
                style="width: 430px"
                multiple
                placeholder="请选择"
                @remove-tag="deleteTag"
                @change="changeRole"
              >
                <el-option
                  v-for="item in roles2"
                  :key="item.name"
                  :disabled="level !== 1 && item.level <= level"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-tooltip effect="dark" content="请先选择公司！" placement="top-start">
              <el-button size="mini" type="text" icon="el-icon-warning" />
            </el-tooltip>
            <el-form-item label="状态">
              <el-radio-group v-model="form.enabled" :disabled="form.id === user.id">
                <el-radio
                  v-for="item in dict.user_status"
                  :key="item.id"
                  :label="item.value"
                >{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label-width="100px" label="股份级勋章" prop="headMedalConfigs" style="display: block;">
              <el-select v-model="form.headMedalConfigs" :disabled="!isHead" multiple placeholder="请选择勋章">
                <el-option v-for="item in headAllocation" :key="item.medalId" :label="item.name" :value="item.medalId">
                  <div style="display: flex;align-items: center;gap: 10px;">
                    <img style="width: 30px;height: 30px;" :src="iconMap.get(Number(item.icon))" alt="">
                    <span>{{ item.name }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label-width="100px" label="子公司勋章" prop="currentMedalConfigs" style="display: block;">
              <el-select v-model="form.currentMedalConfigs" multiple placeholder="请选择勋章">
                <el-option v-for="item in currentAllocation" :key="item.medalId" :label="item.name" :value="item.medalId">
                  <div style="display: flex;align-items: center;gap: 10px;">
                    <img style="width: 30px;height: 30px;" :src="iconMap.get(Number(item.icon))" alt="">
                    <span>{{ item.name }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 350px)" :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
          <el-table-column :selectable="checkboxT" type="selection" width="55" />
          <el-table-column :show-overflow-tooltip="true" prop="username" label="用户名" sortable />
          <el-table-column :show-overflow-tooltip="true" prop="nickName" label="姓名" />
          <el-table-column :show-overflow-tooltip="true" label="勋章" width="130">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" style="display: flex;gap: 4px;">
                  <p v-for="(item,key) in scope.row.medalConfigs" :key="key">{{ item.name }}</p>
                </div>
                <div style="overflow: hidden;text-overflow:ellipsis;width: 100%;">
                  <img v-for="(item,key) in scope.row.medalConfigs" :key="key" style="width: 30px;height: 30px;" :src="iconMap.get(Number(item.icon))">
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="site" label="分站点" sortable>
            <template slot-scope="scope">
              <div>{{ scope.row.site?scope.row.site.name:'' }}</div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="internalQualification" label="内部资质">
            <template slot-scope="scope">
              {{ dict.label.internal_qualification[scope.row.internalQualification] }}
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="practiceQualification" label="执业资格" :formatter="formatPracticeQualification" />
          <el-table-column :show-overflow-tooltip="true" prop="roles" label="平台角色" :formatter="formatRoles" sortable />
          <el-table-column :show-overflow-tooltip="true" prop="userDesktop" label="设计平台" :sort-method="sortUserDesktopKind" width="100" sortable>
            <template slot-scope="scope">
              <div v-if="scope.row.userDesktop">
                {{ scope.row.userDesktop ? formatKind(scope.row.userDesktop.kind):'' }}
                <el-tooltip slot="right" effect="dark" content="切换" placement="top-start">
                  <el-button v-permission="permission.switch" style="margin-left: 2px" :disabled="scope.row.userDesktop.status===0" class="filter-item" size="mini" type="primary" icon="el-icon-sort" @click="doSwitch([scope.row.userDesktop.userId])" />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="状态" align="center" prop="enabled" width="70" sortable>
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enabled"
                :disabled="user.id === scope.row.id"
                @change="changeEnabled(scope.row, scope.row.enabled)"
              />
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="createTime" width="135" label="创建日期" sortable />
          <el-table-column
            v-if="checkPer(['admin','user:edit','user:del','user:project'])"
            label="操作"
            width="260"
            align="center"
          >
            <template slot-scope="scope">
              <udOperation
                :data="scope.row"
                :permission="permission"
                :disabled-dle="scope.row.id === user.id"
              >
                <el-button slot="left" size="mini" type="text" icon="el-icon-refresh" @click="hanleResetPass(scope.row)">重置密码</el-button>
                <el-button slot="right" size="mini" type="text" @click="relatedProject(scope.row)"><svg-icon icon-class="project" /> 相关项目</el-button>
              </udOperation>
            </template>
          </el-table-column>
        </el-table>
        <!-- 相关项目 -->
        <el-dialog class="abow_dialog" view-related-projects :close-on-click-modal="false" :title="childParams.title" :visible.sync="relatedProjectShow" :destroy-on-close="false">
          <related-projects ref="relatedProjects" :child-params="childParams" :related-project-show.sync="relatedProjectShow" />
        </el-dialog>
        <!--分页组件-->
        <pagination />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudUser, { userDesktopSwitch, getSiteList, resetPass } from '@/api/system/user'
import { isvalidPhone } from '@/utils/validate'
import { getDepts, getDeptSuperiorIsDataScope } from '@/api/system/dept'
import { selectAllocationList } from '@/api/system/medal'
import { iconMap } from '../medal/config'
import { getAll, getLevel } from '@/api/system/role'
// import { getAllJob } from '@/api/system/job'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import rrOperation from '@brotherCrud/RR.operation'
import crudOperation from '@brotherCrud/CRUD.operation'
import udOperation from '@brotherCrud/UD.operation'
import pagination from '@brotherCrud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import RelatedProjects from './RelatedProjects'
import { mapGetters } from 'vuex'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
let userRoles = []
let userPracticeQualifications = []
const defaultForm = { id: null, username: null, nickName: null, gender: '男', email: null, enabled: 'false', roles: [], jobName: null, dept: { id: null }, phone: null, wxNo: '', siteId: null, discipline: null, internalQualification: null, practiceQualification: [] }
export default {
  name: 'User',
  components: { crudOperation, rrOperation, udOperation, pagination, DateRangePicker, RelatedProjects, Treeselect },
  cruds() {
    return CRUD({ title: '用户', url: 'api/users', crudMethod: { ...crudUser }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status', 'practice_qualification', 'internal_qualification', 'discipline'],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      relatedProjectShow: false, // 显示相关项目
      childParams: {
        title: '相关项目',
        type: Object,
        userId: null,
        username: null,
        nickName: null
      },
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '', depts: [], deptDatas: [], practiceQualifications: [], level: 3, roles: [], roles2: [],
      // jobs: [],
      practiceQualificationDatas: [], roleDatas: [], // 多选时使用
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      siteList: [], // 站点列表
      siteList2: [], // 弹框站点列表
      roleDefaultSelect: [], // 角色的默认值
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del'],
        download: ['admin', 'user:download'],
        switch: ['admin', 'userDesktop:switch']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '激活' },
        { key: 'false', display_name: '锁定' }
      ],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        'dept.id': [
          { required: true, message: '请选择公司', trigger: 'change' }
        ],
        wxNo: [
          { min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: 'blur' }
        ],
        siteId: [
          { required: true, message: '分站点不能为空', trigger: 'blur' }
        ]
        // jobDatas: [
        //   { required: true, message: '请选择岗位', trigger: 'blur,change', type: 'array' }
        // ],
        // roleDatas: [
        //   { required: true, message: '请选择平台角色', trigger: 'blur,change', type: 'array' }
        // ]
      },
      currentAllocation: [],
      headAllocation: [],
      iconMap: iconMap,
      currentDeptName: '',
      isHead: false
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  watch: {
    // 公司为空，平台角色为空
    'form.dept.id': {
      handler: function handler() {
        if (!this.form.dept.id) {
          this.roleDatas = []
          this.roleDefaultSelect = []
          this.roles2 = []
          this.form.siteId = null
          this.siteList2 = []
        }
      }
    }
  },
  created() {
  /*  this.currentDeptName = JSON.parse(localStorage.getItem("projectObject")).deptName*/
    this.crud.msg.add = '新增成功，用户名及默认密码已发送到用户邮箱。'
    this.hanleSiteList()// 获取站点列表
    this.getRoles()// 获取角色列表
    this.getRoleLevel()
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    changeRole(value) {
      userRoles = []
      value.forEach(function(data, index) {
        const role = { id: data }
        userRoles.push(role)
      })
    },
    changePracticeQualification(value) {
      userPracticeQualifications = []
      value.forEach(function(data, index) {
        const practiceQualification = { id: data }
        userPracticeQualifications.push(practiceQualification)
      })
    },
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    // 删除职业资格
    deletePractice(value) {
      userPracticeQualifications.forEach(function(data, index) {
        if (data.id === value) {
          userPracticeQualifications.splice(index, value)
        }
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      console.log(form)
      if (form.id == null) {
        this.getDepts()
      } else {
        this.getSupDepts(form.dept.id)
        this.getRoles2(form.dept)
        this.getSelectAllocationList(form.dept.id)
      }
      // this.getJobs()
      form.enabled = form.enabled.toString()
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.practiceQualificationDatas = []
      this.roleDatas = []
      this.roleDefaultSelect = []
    },
    // 初始化编辑时候的平台角色与岗位
    [CRUD.HOOK.beforeToEdit](crud, form) {
      // this.getJobs(this.form.dept.id)
      this.practiceQualificationDatas = []
      userPracticeQualifications = []
      const _this = this
      this.roleDatas = []
      userRoles = []
      const roleDefaultSelect = []
      form.roles.forEach(function(role, index) {
        if (_this.level !== 1 && role.level <= _this.level) {
          roleDefaultSelect.push(role.id)
        }
        _this.roleDatas.push(role.id)
        _this.roleDatas.sort((a, b) => roleDefaultSelect.indexOf(b) - roleDefaultSelect.indexOf(a))
        const rol = { id: role.id }
        userRoles.push(rol)
      })
      _this.roleDefaultSelect = roleDefaultSelect
      if (typeof (form.practiceQualification) === 'string' && form.practiceQualification) {
        const practiceQualification = JSON.parse(form.practiceQualification)
        practiceQualification.forEach(function(practiceQualification, index) {
          _this.practiceQualificationDatas.push(practiceQualification.id)
          const data = { id: practiceQualification.id }
          userPracticeQualifications.push(data)
        })
      }
      _this.form.siteId = form.site.siteId
      if (form?.currentMedalConfigs?.length) form.currentMedalConfigs = form.currentMedalConfigs.map(item => item.medalId)
      if (form?.headMedalConfigs?.length) form.headMedalConfigs = form.headMedalConfigs.map(item => item.medalId)
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (!crud.form.dept.id) {
        this.$message({
          message: '公司不能为空',
          type: 'warning'
        })
        return false
      } else if (this.roleDatas.length === 0) {
        this.$message({
          message: '平台角色不能为空',
          type: 'warning'
        })
        return false
      }
      crud.form.roles = userRoles
      crud.form.practiceQualification = userPracticeQualifications
      crud.form.site = {
        siteId: this.form.siteId
      }
      crud.form.medalConfigs = [...crud.form.currentMedalConfigs, ...crud.form.headMedalConfigs]
      crud.form.medalConfigs = crud.form.medalConfigs.map(item => ({ medalId: item }))
      return true
    },
    // 获取左侧公司数据
    getDeptDatas(node, resolve) {
      this.deptName.replace(/(^\s+)|(\s+$)/g, '')
      const sort = 'id,desc'
      const params = { sort: sort, isDataScope: true }
      if (typeof node !== 'object') {
        if (node) {
          params['name'] = node
        }
      } else if (node.level !== 0) {
        params['pid'] = node.data.id
      }
      setTimeout(() => {
        getDepts(params).then(res => {
          if (resolve) {
            resolve(res.content)
          } else {
            this.deptDatas = res.content
          }
        })
      }, 100)
    },
    getDepts() {
      getDepts({ enabled: true, isDataScope: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getSupDepts(deptId) {
      getDeptSuperiorIsDataScope(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内公司数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id, isDataScope: true }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 切换公司
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.query.deptId = null
      } else {
        this.query.deptId = data.id
      }
      this.crud.toQuery()
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.user_status[val] + '" ' + data.username + ',再次激活密码将被重置， 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudUser.edit(data).then(res => {
          this.crud.notify(this.dict.label.user_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.refresh()
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    // 获取列表内平台角色数据
    getRoles() {
      // type 1平台   2项目
      const params = {
        type: 1
      }
      getAll(params).then(res => {
        this.roles = res
      }).catch(() => { })
    },
    // 获取弹窗内平台角色数据
    getRoles2(i) {
      // type 1平台   2项目
      const params = {
        type: 1
      }
      // true 外部  false内部
      // inexternal  1内部  2外部
      if (i.isExternal) {
        params.inexternal = 2
      } else {
        params.inexternal = 1
      }
      getAll(params).then(res => {
        if (i.name !== '上海本部') {
          this.roles2 = res.filter(object => object.name !== '上海本部用户')
        } else {
          this.roles2 = res
        }
      }).catch(() => { })
    },
    // 获取弹窗内岗位数据
    // getJobs() {
    //   getAllJob().then(res => {
    //     this.jobs = res.content
    //   }).catch(() => { })
    // },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => { })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    },
    // 格式化设计平台
    formatKind(rowData) {
      let x = null
      switch (rowData) {
        case 1:x = '纵骥'
          break
        case 2:x = '泛云'
          break
        default:
          x = '种类未知'
      }
      return x
    },
    // 格式化切换云平台
    formatKind2(rowData) {
      let x = null
      switch (rowData) {
        case 1:x = '泛云'
          break
        case 2:x = '纵骥'
          break
        default:
          x = '种类未知'
      }
      return x
    },
    // 格式化执业资格
    formatPracticeQualification(row) {
      let practiceQualification = ''
      if (row.practiceQualification) {
        const practiceQualifications = JSON.parse(row.practiceQualification)
        practiceQualifications.forEach(item => {
          if (practiceQualification !== '') {
            practiceQualification = practiceQualification + '，' + this.dict.label.practice_qualification[item.id]
          } else {
            practiceQualification = this.dict.label.practice_qualification[item.id]
          }
        })
      }
      return practiceQualification
    },
    // 格式化平台角色
    formatRoles(row) {
      let role = ''
      row.roles.forEach(item => {
        if (role !== '') {
          role = role + '，' + item.name
        } else {
          role = item.name
        }
      })
      return role
    },
    // 切换
    doSwitch(userId) {
      let kind = null
      this.crud.data.map(item => {
        if (item.userDesktop.userId === userId[0]) {
          kind = item.userDesktop.kind
        }
      })
      this.$confirm('确定切换至' + this.formatKind2(kind) + '吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.sureSwitch(userId)
      })
    },
    // 确定切换
    sureSwitch(userId) {
      userDesktopSwitch(userId).then(() => {
        this.crud.notify('切换成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.crud.toQuery()
      })
    },
    // 排序
    sortDeptName(obj1, obj2) {
      return obj1.dept.name.localeCompare(obj2.dept.name, 'zh-CN')
    },
    sortUserDesktopKind(obj1, obj2) {
      return this.formatKind(obj1.userDesktop.kind).localeCompare(this.formatKind(obj2.userDesktop.kind), 'zh-CN')
      // 按value排序
      // if (obj1.userDesktop.kind > obj2.userDesktop.kind) {
      //   return -1  // 如果返回值小于0 那么a排在前 b在之后， 等于0 位置不变， 大于0 b排在a之前
      // }
    },
    // 获取站点列表
    hanleSiteList() {
      getSiteList({}).then(data => {
        if (data) {
          this.siteList = data.map(object => {
            return {
              value: object.siteId,
              label: object.name
            }
          })
        }
      })
    },
    // 获取弹框站点列表
    hanleSiteList2() {
      getSiteList({}).then(data => {
        if (data) {
          this.siteList2 = data.map(object => {
            return {
              value: object.siteId,
              label: object.name
            }
          })
        }
      })
    },
    // 切换公司
    selectDept(val) {
      if (val.sites.length > 0) {
        this.form.siteId = val.sites[0].siteId
      } else {
        this.form.siteId = ''
      }
      this.roleDatas = []
      this.hanleSiteList2()// 获取弹框站点列表
      // true 外部  false内部
      this.getRoles2(val)
      this.form.medalConfigs = []
      this.form.headMedalConfigs = []
      this.form.currentMedalConfigs = []
      this.getSelectAllocationList(val.id)
    },
    // 重置密码
    hanleResetPass(row) {
      if (row.id) {
        this.$confirm(`确认重置密码?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const params = {
            userId: row.id
          }
          resetPass(params).then(() => {
            this.crud.notify('重置密码成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          })
        })
      }
    },
    /* 显示相关项目*/
    relatedProject(row) {
      this.relatedProjectShow = true
      this.childParams.userId = row.id
      this.childParams.username = row.username
      this.childParams.nickName = row.nickName
      if (this.$refs.relatedProjects !== undefined) {
        this.$refs.relatedProjects.crud.toQuery()
      }
    },
    getSelectAllocationList(deptId) {
      selectAllocationList({ deptId }).then(res => {
        this.currentAllocation = res.currentAllocation
        this.headAllocation = res.headAllocation
        this.isHead = res.isHead
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import "~@/assets/styles/variables.scss";
  ::v-deep .star>.el-form-item__label:before{
    content: "*";
    color: #ff4949;
    margin-right: 4px;
  }
</style>
